package com.peng.mybatis.scripting;

import cn.hutool.core.lang.Assert;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;

public class LanguageDriverRegistry {

    private final Map<Class<?>, LanguageDriver> LANGUAGE_DRIVERS = new HashMap<>();

    @Getter
    private Class<?> defaultDriverClass = null;

    public void register(Class<?> cls) {
        Assert.notNull(cls, "语言驱动类型不能为空");
        Assert.isTrue(LanguageDriver.class.isAssignableFrom(cls), "类型不为：{}", cls.getName());
        LanguageDriver driver = LANGUAGE_DRIVERS.get(cls);
        if (driver == null) {
            try {
                driver = (LanguageDriver) cls.getDeclaredConstructor().newInstance();
                LANGUAGE_DRIVERS.put(cls, driver);
            } catch (Exception e) {
                throw new RuntimeException("加载语言驱动器失败", e);
            }
        }
    }

    public LanguageDriver getDriver(Class<?> cls) {
        return LANGUAGE_DRIVERS.get(cls);
    }

    public LanguageDriver getDefaultDriver() {
        return getDriver(getDefaultDriverClass());
    }

    public void setDefaultDriverClass(Class<?> defaultDriverClass) {
        register(defaultDriverClass);
        this.defaultDriverClass = defaultDriverClass;
    }

}
